import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const apiRoot = path.resolve(__dirname, '../docs/api');
const outputJson = path.resolve(__dirname, '../docs/config/sidebars/api.json');

function scanClasses(dir) {
    const items = [];

    function walk(current) {
        const entries = fs.readdirSync(current);
        for (const entry of entries) {
            const full = path.join(current, entry);
            const stat = fs.statSync(full);
            if (stat.isDirectory()) {
                walk(full);
            } else if (entry.endsWith('.md') && full.includes(`${path.sep}classes${path.sep}`)) {
                const relPath = full.replace(apiRoot, '').replace(/\\/g, '/').replace(/\.md$/, '');
                const name = relPath.split('/').pop();
                items.push({
                    text: name,
                    link: `/api${relPath}`
                });
            }
        }
    }

    walk(dir);

    return [
        {
            text: 'API 文档',
            collapsed: false,
            items
        }
    ];
}

const sidebarData = scanClasses(apiRoot);
fs.mkdirSync(path.dirname(outputJson), { recursive: true });
fs.writeFileSync(outputJson, JSON.stringify(sidebarData, null, 2), 'utf-8');

console.log(`✅ 已生成 sidebar 到: ${outputJson}`);